﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Collections;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using Lucene.Net.Support;

namespace NetWorkCardConnect
{
    public partial class Form1 : Form
    {

        private HashMap<string, string> hashMap = new HashMap<string, string>();

        //https://docs.microsoft.com/zh-cn/windows/win32/cimwin32prov/win32-networkadapter
        private ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * From Win32_NetworkAdapter");

        public Form1()
        {
            InitializeComponent();
            NetWorkList();
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);//在网络接口的 IP 地址更改时发生。

            NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;//在网络的可用性更改时发生。
        }

        private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            Console.WriteLine("network change");
        }

        private void AddressChangedCallback(object sender, EventArgs e)
        {

            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface n in adapters)
            {
                Console.WriteLine("   {0} is {1}", n.Name, n.OperationalStatus);
            }
        }
        
        
        /// <summary>
        /// 网卡列表
        /// </summary>
        public void NetWorkList()
        {
            
             ManagementObjectCollection collection = searcher.Get();
             List<string> netWorkList = new List<string>();

             foreach (ManagementObject obj in collection)
             {
                 //只显示正常网卡以及在控制面板【网络连接】中显示的网卡
                 if (obj["ConfigManagerErrorCode"] !=null&&obj["NetConnectionID"]!=null)
                 {
                    string NetConnectionID = obj["NetConnectionID"].ToString();
                    string GUID = obj["GUID"].ToString(); ;
                    netWorkList.Add(NetConnectionID);
                    hashMap.Add(NetConnectionID, GUID);
                 }
             }
             this.cmbNetWork.DataSource = netWorkList;
        }

        /// <summary>
        /// 禁用网卡
        /// </summary>5
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool DisableNetWork(string guid)
        {
            try
            {
                ManagementObject managementObject = GetManagementObject(guid);
                if (managementObject == null)
                {
                    return false;
                }
                managementObject.InvokeMethod("Disable", null);
                return IsDisEnable(guid);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        /// <summary>
        /// 启用网卡
        /// </summary>
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool EnableNetWork(string guid)
        {
            try
            {
                ManagementObject managementObject=GetManagementObject(guid);
                if (managementObject==null)
                {
                    return false;
                }
                managementObject.InvokeMethod("Enable", null);
                return IsEnable(guid);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }

        }

        /// <summary>
        /// 网卡状态
        /// </summary>
        /// <param name="GUID">网卡名</param>
        /// <returns></returns>
        public bool IsEnable(string guid)
        {
            ManagementObject managementObject = GetManagementObject(guid);
            if (managementObject == null)
            {
                return false;
            }
            return managementObject["ConfigManagerErrorCode"] != null && (uint)managementObject["ConfigManagerErrorCode"] == 0;//0 为正常 22代表禁用
        }

        public bool IsDisEnable(string guid)
        {
           ManagementObject managementObject= GetManagementObject(guid);
           if (managementObject==null)
           {
               return false;
           }
           return managementObject["ConfigManagerErrorCode"] != null && (uint)managementObject["ConfigManagerErrorCode"] == 22;//0 为正常 22代表禁用
             
        }

        /// <summary>
        /// 得到指定网卡
        /// </summary>
        /// <param name="GUID">网卡全局唯一GUID</param>
        /// <returns></returns>
        private ManagementObject GetManagementObject(string guid)
        {
            ManagementObjectCollection managementObjectCollection = searcher.Get();
            if (managementObjectCollection==null)
            {
                return null;
            }
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                if (managementObject["ConfigManagerErrorCode"] != null && managementObject["GUID"] != null && managementObject["GUID"].ToString() == guid)
                {
                    return managementObject;
                }
            }
            return null;
        }

        /// <summary>
        /// 开启网卡
        /// </summary>
        public void StartNetWork()
        {
                if (!EnableNetWork(hashMap[this.cmbNetWork.SelectedValue.ToString()]))
                {
                    this.InsertLog("开启网卡失败!");
                    btnStart.Enabled = true;
                    btnStop.Enabled = false;

                }
                else
                {
                    this.InsertLog("开启网卡成功!");
                    btnStart.Enabled = false;
                    btnStop.Enabled = true;
 
                }
        }

        /// <summary>
        /// 关闭网卡
        /// </summary>
        public void StopNewWork()
        {
                if (!DisableNetWork(hashMap[this.cmbNetWork.SelectedValue.ToString()]))
                {
                    this.InsertLog("禁用网卡失败!");
                    btnStart.Enabled = false;
                    btnStop.Enabled = true;
                }
                else
                {
                    this.InsertLog("禁用网卡成功!");
                    btnStart.Enabled = true;
                    btnStop.Enabled = false;
                }
        }

        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="msg"></param>
        public void InsertLog(string msg)
        {
            if (this.richTextBox1.Lines.Count() > 100)
            {
                richTextBox1.Clear();
            }
            string str = String.Format("[{0}]--[{1}]-->{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), this.cmbNetWork.Text.Trim(), msg) + Environment.NewLine;
            richTextBox1.Text = richTextBox1.Text.Insert(0, str);
        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            this.InsertLog("网卡开启中……");
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            this.StartNetWork();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.InsertLog("网卡禁用中……");
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            this.StopNewWork();
        }
       

        private void cmbNetWork_SelectedIndexChanged(object sender, EventArgs e)
        {

            string NetConnectionID = cmbNetWork.SelectedItem.ToString();
            string guid=hashMap[NetConnectionID];
            ManagementObject managementObject=GetManagementObject(guid);
            if (managementObject==null)
            {
                return;
            }
            uint code = (uint)managementObject["ConfigManagerErrorCode"];
            if (code == 0)//0代表正常
            {
                btnStart.Enabled = false;
                btnStop.Enabled = true;
            }
            else if (code == 22)//22代表禁用
            {
                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
            else
            {
                btnStart.Enabled = false;
                btnStop.Enabled = false;
            }
            listView1.Items.Clear();
            //网卡属性信息
            //属性代表的意思可以查看官方文档说明 https://docs.microsoft.com/zh-cn/windows/win32/cimwin32prov/win32-networkadapter
            foreach (PropertyData prop in managementObject.Properties)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = prop.Name;
                object data = managementObject[prop.Name];
                if (data != null)
                {
                    lvi.SubItems.Add(data.ToString());
                }
                else
                {
                    lvi.SubItems.Add("null");
                }
                listView1.Items.Add(lvi);

            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            NetWorkList();
        }
    }
}
